// pages/fuli/fuli.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //优惠券
    list: [],
    logo: '',
    isShowGetUserInfo: false
  },

  /**
   * 分享
   */
  share(e) {
    if (e.currentTarget.dataset['num'] > 0) {
      wx.navigateTo({
        url: '/pages/guidanceStudy/fuli_share/fulishare?local_policy_id=' + e.currentTarget.dataset['id'] + '&logo=' + this.data.logo
      });
    } else {
      wx.showToast({
        title: '优惠券已用完',
        icon: 'none'
      });
    }
  },

  //授权获取个人头像和昵称
  getUserInfo(e) {
    if (e.detail.userInfo) {
      this.setData({
        'isShowGetUserInfo': false
      })
      wx.setStorageSync('wx_head', e.detail.userInfo.avatarUrl);
      wx.setStorageSync('wx_name', e.detail.userInfo.nickName);
      wx.login({
        success: res => {
          wx.setStorageSync('code', res.code);
          this.parseUnionID(e.detail.encryptedData, e.detail.iv);
        }
      })
      wx.showToast({
        title: '获取个人信息成功',
        icon: 'none'
      });
    } else {
      wx.showToast({
        title: '个人信息授权失败',
        icon: 'none'
      });
      wx.redirectTo({
        url: 'pages/guidanceStudy/fuli/fuli'
      });
    }
  },
  //授权
  getSetting() {
    wx.getSetting({
      success: res => {
        //没授权过
        if (!res.authSetting['scope.userInfo']) {
          wx.hideLoading();
          this.setData({
            isShowGetUserInfo: true
          })
        } else {
          this.isRegister(wx.getStorageSync('union_id'));
        }
      }
    })
  },
  /**
   * 解析unionID
   */
  parseUnionID(encryptedData, iv) {
    wx.showLoading({
      title: '拼命加载中...',
    });
    wx.request({
      url: app.globalData.url + 'c=home&m=getPhoneNumber',
      data: {
        'encryptedData': encryptedData,
        'iv': iv,
        'code': wx.getStorageSync('code')
      },
      success: (res) => {
        res = res.data;
        if (res.status == 200) {
          //保存unionID到本地
          // var phone = res.data.purePhoneNumber;
          var union_id = res.data.unionId;
          wx.setStorageSync('union_id', union_id);
          this.isRegister(union_id);
        } else {
          wx.showToast({
            title: '获取个人信息失败，请重试',
            icon: 'none'
          })
          this.setData({
            getPhoneNumberChange: true
          })
        }
      }
    })
  },
  //判断unionID是否注册
  isRegister(union_id) {
    wx.request({
      url: app.globalData.url + 'c=user&m=isRegister',
      data: {
        union_id: union_id
      },
      success: res => {
        wx.hideLoading();
        res = res.data;
        if (res.status == 200) {
          if (res.data.is_register != 0) {
            //已注册
            wx.setStorageSync('user_id', res.data.user_id);
            app.globalData.userId = res.data.user_id;
            wx.request({
              url: app.globalData.url + 'c=policy&m=lists&user_id=' + wx.getStorageSync('user_id'),
              success: res => {
                res = res.data;
                if (res.status === 200) {
                  const list = res.data.policy_info;
                  var total_number = 0;
                  for (let i = 0; i < list.length; i++) {
                    total_number = total_number + list[i]['surplus_number'];
                  }
                  //赋值渲染
                  this.setData({
                    'list': list,
                    'total_number': total_number,
                    'logo': res.data.logo
                  })
                  //上传头像和手机号码
                  wx.request({
                    url: app.globalData.url + 'c=user&m=keepWeChat',
                    data: {
                      user_id: res.data.id,
                      wx_head: wx.getStorageSync('wx_head'),
                      wx_name: wx.getStorageSync('wx_name')
                    },
                    success: res => {
                      wx.hideLoading();
                      res = res.data;
                    }
                  })
                } else {
                  wx.showToast({
                    title: res.msg,
                    icon: 'none'
                  })
                }
              }
            });
          } else {
            wx.redirectTo({
              url: '/pages/welcome/applydesc/applydesc'
            });
          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          });
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    wx.showLoading({
      title: '拼命加载中...',
    })
    if (wx.getStorageSync('user_id')) {
      wx.request({
        url: app.globalData.url + 'c=policy&m=lists&user_id=' + wx.getStorageSync('user_id'),
        success: res => {
          wx.hideLoading();
          res = res.data;
          if (res.status === 200) {
            const list = res.data.policy_info;
            var total_number = 0;
            for (let i = 0; i < list.length; i++) {
              total_number = total_number + list[i]['surplus_number'];
            }
            //赋值渲染
            this.setData({
              'list': list,
              'total_number': total_number,
              'logo': res.data.logo
            })
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'none'
            })
          }
        },
        fail: () => {
          wx.showToast({
            title: '',
            icon: 'none'
          })
        }
      })
    } else {
      this.getSetting();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})